import java.io.*;

public class Sessions{
	
	private File lock = new File("/home/joselito/Desktop/SD/servidor/interface/web/WEB-INF/classes/lock");
	private String sessionFile="/home/joselito/Desktop/SD/servidor/interface/web/WEB-INF/classes/sessions";

	public Sessions() {
		
	}

	private void lockFile() { //TODO
		
	}

	private void unlockFile(){ //TODO
		
	}

	public boolean isValid(String token) throws FileNotFoundException, IOException{
		lockFile();
		BufferedReader sessions = new BufferedReader(new FileReader(sessionFile));
		String line;
		do{
			line=sessions.readLine();
			sessions.readLine();
			sessions.readLine();
		}while((line!=null)&&(!line.equals(token)));
		sessions.close();
		unlockFile();
		if (line==null)
			return false;
		else
			return true;
	}

	public String getUser(String token) throws FileNotFoundException, IOException{
		lockFile();
		BufferedReader sessions = new BufferedReader(new FileReader(sessionFile));
		String line;
		do{
			line=sessions.readLine();
		}while((!line.equals(token))&&(line!=null));
		sessions.close();
		unlockFile();
		if (line==null)
			return "";
		else
			return sessions.readLine();
	}

	public String getHomePath(String token) throws FileNotFoundException, IOException{
		lockFile();
		BufferedReader sessions = new BufferedReader(new FileReader(sessionFile));
		String line;
		do{
			line=sessions.readLine();
		}while((!line.equals(token))&&(line!=null));
		sessions.close();
		unlockFile();
		if (line==null)
			return "";
		else{
			sessions.readLine();
			return sessions.readLine();
		}
	}

	public void createSession(String token, String user, String homePath) throws IOException{
		lockFile();
		BufferedWriter sessions = new BufferedWriter(new FileWriter(sessionFile));
		sessions.write(token+"\n");
		sessions.write(user+"\n");
		sessions.write(homePath+"\n");
		sessions.close();
		unlockFile();
	}

	public void removeSession (String token) throws FileNotFoundException, IOException{
		lockFile();
		File inFile = new File("sessions");
		File tempFile = new File("sessions.tmp");

		BufferedReader br = new BufferedReader(new FileReader(sessionFile));
		PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

		String line = null;

		//Read from the original file and write to the new
		//unless content matches data to be removed.
		while ((line = br.readLine()) != null) {

			if (!line.trim().equals(token)) {
				pw.println(line);
				pw.flush();
			}
			else{
				br.readLine();
				br.readLine();
			}
		}
		pw.close();
		br.close();

		//Delete the original file
		inFile.delete();

		//Rename the new file to the filename the original file had.
		tempFile.renameTo(inFile);
		unlockFile();
	}
} 

